package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.contant.MqContant;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;

import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听延迟队列
 */
@Component
@RequiredArgsConstructor
public class TradeDelayListener {
    private final IOrderService orderService;
    private final PayClient payClient;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqContant.TRADE_DELAY_QUEUE, durable = "true"),
            exchange = @Exchange(value = MqContant.TRADE_DELAY_EXCHANGE),
            key = {MqContant.TRADE_DELAY_KEY}
    ))
    /**
     * 获取交易订单信息的延迟消息
     */
    public void getTradeDelayMessage(Long id) {
        Order order = orderService.getById(id);
        //Order表支付过了
        if (order == null || order.getStatus() != 1) {
            return;
        }
        //Order报未支付，但是支付流水表可能支付了
        PayOrderDTO payOrderDTO = payClient.queryPayOrderById(id);
        if (payOrderDTO.getStatus() != 1) {
            //肯定支付了
            return;
        } else {
            //改单未支付,回复库存，
            orderService.cancelOrder(id);
        }
    }

}
